Steps:
- pick up the next item in the list
- look at all the previous elements in the list, and move it to the appropriate position
- repeat until we've done all the items
e.g. for
[12, 6, 21, 5, 9]
- we start with
12. There are no previous elements, so we move onto the next item. - We look at
6. Comparing it to the only previous element6we can see that we want to move it before12, so our list should look like[6, 12, 21, 5, 9]. - We look at
21, and compare it to the previous elements. First we compare21and12– clearly21is greater than12(and we know that the previous elements must all be sorted, so we can stop there). - We look at
5.5is smaller than21, so we compare it to the previous element.5is also smaller than12so we turn to look at6.5is less than6. Therefore our list is now[5, 6, 12, 21, 9] - We now look at
9.9is less than21, so we look at12.9is less than12, so we look at6.9is greater than6, so we insert9after6. Our list is now[5, 6, 9, 12, 21]
The final list is therefore [5, 6, 9, 12, 21].